<?php

namespace app\api\controller;

use app\api\validation\Address;
use app\services\AddressService;
use app\services\GoodsService;
use support\Db;
use support\Request;

class AddressController
{
    public function add(Request $request)
    {
        try {
            $validate = new Address();

            if (! $validate->check($request->post())) {
                throw new \Exception($validate->getError());
            }


            $data = $request->post();
            if (strlen($data['contact_mobile']) != 11) {
                throw new \Exception('错误的手机格式');
            }

            AddressService::add($data);

            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function show(Request $request)
    {
        try {
            $data = $request->post();
            $data = AddressService::detail($data['id']);

            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function edit(Request $request)
    {
        try {
            $validate = new Address();

            if (! $validate->check($request->post())) {
                throw new \Exception($validate->getError());
            }

            $data = $request->post();
            AddressService::edit($data['id'], $data);
            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function list(Request $request)
    {
        try {
            $data = AddressService::list();
            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function delete(Request $request)
    {
        try {
            AddressService::delete($request->post('id'));
            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function setDefault(Request $request)
    {
        try {
            AddressService::setDefault($request->post('id'));
            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }
}